package com.iamteer.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iamteer.entity.Admin;
import com.iamteer.exception.UserExistsException;
import com.iamteer.service.IAdminService;
import com.iamteer.service.impl.AdminService;

/**
 * 4. 控制层开发
 */
@WebServlet("/admin")
public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private IAdminService adminService = new AdminService();
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AdminServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取操作类型
		String method = request.getParameter("method");
		if ("register".equals(method)) {
			register(request, response);
		}
	}

	/**
	 * 注册处理方法
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void register(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		//1 获取请求参数
		String userName = request.getParameter("userName");
		String pwd = request.getParameter("pwd");
//		System.out.println(userName + "-------" + pwd);
		//封装
		Admin admin = new Admin();
		admin.setUsername(userName);
		admin.setPassword(pwd);
		
		try {
			adminService.register(admin);
			//注册成功，跳转到首页
			request.getRequestDispatcher("/index.jsp").forward(request, response);
		} catch (UserExistsException e) {
			//用户名存在，注册失败
			request.setAttribute("message", "用户名已经存在");
			//转发
			request.getRequestDispatcher("/register.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			//其他错误，跳转到错误页面
			response.sendRedirect(request.getContextPath() + "/error/error.jsp");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
